package com.android.lovingpet.adopt.adoption.view;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.lovingpet.R;
import com.android.lovingpet.bean.Pet;
import com.android.lovingpet.common.OnItemClickListener;
import com.bumptech.glide.Glide;

import java.util.ArrayList;
import java.util.List;

import butterknife.OnClick;

/**
 * Created by ikata on 2018/4/3.
 */

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> implements View.OnClickListener{
    private List<Pet> list=new ArrayList<>();
    private Context context;
    private OnItemClickListener onItemClickListener;

    public RecyclerViewAdapter(List<Pet> list)
    {
        this.list=list;
    }

    public void add(Pet pet)
    {
        list.add(pet);
        notifyItemInserted(list.size());
        notifyItemChanged(list.size());
    }

    public void clear()
    {
        list.clear();
        notifyDataSetChanged();
    }

    public Pet getData(int position)
    {
        return list.get(position);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        context=parent.getContext();
        View view= LayoutInflater.from(context).inflate(R.layout.item_adopt,parent,false);
        view.setOnClickListener(this);
        ViewHolder viewHolder=new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.itemView.setTag(position);
        holder.tv_demand.setText(list.get(position).getDemand());
        holder.tv_variety.setText(list.get(position).getType());
        Glide.with(context)
                .load(list.get(position).getImage())
                .into(holder.im_head);
    }
    @Override
    public int getItemCount() {
        return list.size();
    }

    @Override
    public void onClick(View v) {
        if (onItemClickListener!=null)
        {
            onItemClickListener.onItemClick((Integer) v.getTag());
        }
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener)
    {
        this.onItemClickListener=onItemClickListener;
    }


    public class ViewHolder extends RecyclerView.ViewHolder
    {
        ImageView im_head;
        TextView tv_demand;
        TextView tv_variety;
        public ViewHolder(View itemView) {
            super(itemView);
            im_head=itemView.findViewById(R.id.iv_head);
            tv_demand=itemView.findViewById(R.id.tv_demand);
            tv_variety=itemView.findViewById(R.id.tv_type);
        }
    }
}
